# -*- coding: utf-8 -*-
import uuid

from django import forms
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.contrib.auth.models import User

from userprofiles import settings as up_settings

if up_settings.USE_ACCOUNT_VERIFICATION:
    from userprofiles.contrib.accountverification.models import AccountVerification

if 'userprofiles.contrib.emailverification' in settings.INSTALLED_APPS:
    from userprofiles.contrib.emailverification.models import EmailVerification


class RegistrationForm(forms.ModelForm):
    username = forms.RegexField(
        label=_(u"Usuario"),
        max_length=30,
        widget=forms.TextInput(attrs={'placeholder': _(u'Nombre de usuario')}),
        regex=r'^[\w.-]+$',
        error_messages={
            'invalid': _(u"Sólo se permiten letras, números y los siguientes caracteres ./-/_"),
            'required': _(u"Ingrese un nombre de usuario")
        }
    )

    email = forms.EmailField(
        widget=forms.TextInput(attrs={'placeholder': _(u'Correo electrónico')}),
        max_length=75,
        error_messages={'required': _(u"Ingrese su correo electrónico")},
        label="E-mail"
    )

    email_repeat = forms.EmailField(
        widget=forms.TextInput(attrs={'placeholder': _(u'Confirme su correo electrónico')}),
        max_length=75,
        error_messages={'required': _(u"Confirme su correo electrónico")},
        label=_(u"Confirmar E-mail")
    )

    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'placeholder': _(u'Ingrese una contraseña')}),
        max_length=128,
        error_messages={'required': _(u"Ingrese una contraseña")},
        label=_(u"Contraseña")
    )
    password_repeat = forms.CharField(
        widget=forms.PasswordInput(attrs={'placeholder': _(u'Confirme su contraseña')}),
        max_length=128,
        error_messages={'required': _(u"Confirme su contraseña")},
        label=_(u"Ingrese la contraseña nuevamente")
    )

    first_name = forms.CharField(
        widget=forms.TextInput(attrs={'placeholder': _(u'Ingrese su nombre')}),
        max_length=30,
        error_messages={'required': _(u"Ingrese su nombre")},
        label=_(u"Nombre")
    )

    last_name = forms.CharField(
        widget=forms.TextInput(attrs={'placeholder': _(u'Ingrese sus apellidos')}),
        max_length=30,
        error_messages={'required': _(u"Ingrese sus apellidos")},
        label=_(u"Apellidos")
    )

    def __init__(self, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)

        if not up_settings.DOUBLE_CHECK_EMAIL:
            del self.fields['email_repeat']

        if not up_settings.DOUBLE_CHECK_PASSWORD:
            del self.fields['password_repeat']

        if not up_settings.REGISTRATION_FULLNAME:
            del self.fields['first_name']
            del self.fields['last_name']

        if up_settings.EMAIL_ONLY:
            self.fields['username'].widget = forms.widgets.HiddenInput()
            self.fields['username'].required = False

    def _generate_username(self):
        """ Generate a unique username """
        while True:
            # Generate a UUID username, removing dashes and the last 2 chars
            # to make it fit into the 30 char User.username field. Gracefully
            # handle any unlikely, but possible duplicate usernames.
            username = str(uuid.uuid4())
            username = username.replace('-', '')
            username = username[:-2]

            try:
                User.objects.get(username=username)
            except User.DoesNotExist:
                return username

    def clean_username(self):
        if up_settings.EMAIL_ONLY:
            username = self._generate_username()
        else:
            username = self.cleaned_data['username']
            if User.objects.filter(username__iexact=username):
                raise forms.ValidationError(
                    _(u"Ya existe este nombre de usuario. Por favor ingrese uno diferente"))

        return username

    def clean_email(self):
        if not up_settings.CHECK_UNIQUE_EMAIL:
            return self.cleaned_data['email']

        new_email = self.cleaned_data['email']

        emails = User.objects.filter(email__iexact=new_email).count()
        if 'userprofiles.contrib.emailverification' in settings.INSTALLED_APPS:

            emails += EmailVerification.objects.filter(
                new_email__iexact=new_email, is_expired=False).count()
        if emails > 0:
            raise forms.ValidationError(
                _(u'Este e-mail ya se encuentra registrado. Por favor ingrese uno diferente'))

        return new_email

    def clean(self):
        if up_settings.DOUBLE_CHECK_EMAIL:
            if 'email' in self.cleaned_data and 'email_repeat' in self.cleaned_data:
                if self.cleaned_data['email'] != self.cleaned_data['email_repeat']:
                    raise forms.ValidationError(_(u'Las direcciones de E-mail no concuerdan.'))

        if up_settings.DOUBLE_CHECK_PASSWORD:
            if 'password' in self.cleaned_data and 'password_repeat' in self.cleaned_data:
                if self.cleaned_data['password'] != self.cleaned_data['password_repeat']:
                    raise forms.ValidationError(_(u'Las contraseñas no concuerdan.'))

        return self.cleaned_data

    def send_verification_mail(self, new_user):
        AccountVerification.objects.send_verification_mail(new_user=new_user)

    def save(self, *args, **kwargs):
        if up_settings.USE_ACCOUNT_VERIFICATION:
            new_user = User.objects.create_user(
                username=self.cleaned_data['username'],
                password=self.cleaned_data['password'],
                email=self.cleaned_data['email'],
            )
            new_user.first_name = self.cleaned_data['first_name']
            new_user.last_name = self.cleaned_data['last_name']
            new_user.is_active = False
            new_user.save()
            # new_user = AccountVerification.objects.create_inactive_user(
            #     username=self.cleaned_data['username'],
            #     password=self.cleaned_data['password'],
            #     email=self.cleaned_data['email'],
            #     first_name=self.cleaned_data['first_name'],
            #     last_name=self.cleaned_data['last_name'],
            # )
        else:
            new_user = User.objects.create_user(
                username=self.cleaned_data['username'],
                password=self.cleaned_data['password'],
                email=self.cleaned_data['email'],
            )
            new_user.first_name = self.cleaned_data['first_name']
            new_user.last_name = self.cleaned_data['last_name']
            new_user.save()

        # if up_settings.REGISTRATION_FULLNAME:
        #     new_user.first_name = self.cleaned_data['first_name']
        #     new_user.last_name = self.cleaned_data['last_name']
        #
        #     new_user.save()

        if hasattr(self, 'save_profile'):
            self.save_profile(new_user, *args, **kwargs)

        return new_user

    class Meta():
        model = User
        fields = ('username', 'first_name', 'last_name', 'email')
